#include"comm.h"

int main()
{
    umask(0);////将文件默认掩码设置为0
    if(mkfifo(MYFIFO,0666)<0)  //创建管道
    {
        perror("server mkfifo:");
        return 1;
    }
    int fd = open(MYFIFO,O_RDONLY);//以读方式打开命名管道文件
    if(fd<0)
    {
        perror("server open");
        return 2;
    }
    //处理业务逻辑
    while(1)
    {
        char buffer[1024] = {0};
        ssize_t s = read(fd,buffer,sizeof(buffer)-1);
        /*
        if(s > 0)
        {
            buffer[s] = '\0';
            printf("收到的信息为:%s\n",buffer);
        }
        */
        if(s>0)
        {
            buffer[s] = '\0';
            if(strcmp("show-sl",buffer) == 0)
            {
                if(fork() == 0) //创建子进程帮我们程序替换
                {
                    execl("/usr/bin/sl","sl",NULL);
                    exit(3);
                }
                waitpid(-1,NULL,0);
            }
            else if(strcmp("show-ls-l",buffer) == 0)
            {
                if(fork() == 0) //创建子进程帮我们程序替换
                {
                    execl("/usr/bin/ls","ls","-l",NULL);
                    exit(3);
                }
                waitpid(-1,NULL,0);
            }
            else
            {
                printf("收到的信息为:%s\n",buffer);
            }
        }
        else if(s < 0)
        {
            perror("read:");
            break;
        }
        else // s==0
        {
            printf("对端已经关闭.......\n");
            break;
        }
    }
    close(fd);
    return 0;
}